/*******************************************************************************
 * Copyright (c) 2010 Eugene Vorobkalo.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the GNU Public License v2.0
 * which accompanies this distribution, and is available at
 * http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
 *
 * Contributors:
 *     Eugene Vorobkalo - initial API and implementation
 *     Andrey Fedorov - LOADING PRICES, PRICELISTS and others improv.
 ******************************************************************************/
package org.droidpres.activity;

import java.io.*;
import java.net.SocketTimeoutException;
import java.sql.Date;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import android.content.*;
import org.apache.http.conn.HttpHostConnectException;
import org.droidpres.R;
import org.droidpres.db.DB;
import org.droidpres.db.QueryHelper;
import org.droidpres.utils.Const;
import org.droidpres.utils.Decompress;
import org.droidpres.utils.csv;
import org.xmlrpc.android.XMLRPCClient;
import org.xmlrpc.android.XMLRPCException;
import org.xmlrpc.android.XMLRPCFault;


import android.app.Activity;
import android.app.AlertDialog;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.NetworkInfo;
import android.net.Uri;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.TextView;

public class TransferActivity extends Activity implements OnClickListener{
	private static final int SERVER_MOBILE 		= 0;
	private static final int SERVER_WIFI 		= 1;
    private static final int SERVER_TEST 		= 2;

    private static String LOG_TAG = "TransferActivity";

	private static final int TRANSACTION_LENGTH = 1000;

	private static DecimalFormat cf;

    private static final String temp_dir = SetupRootActivity.getDroidPresDir().concat("Temp/");

	private SQLiteDatabase sDataBase;
    private String sDeviceGUID;

	private boolean sWiFiFlag, sWiFiConnectFlag, sImportFlag, sStartTransferFlag;
	private boolean sNewVersion = false;
	private String sURL = "";

	private boolean bWifi_was_connected = false;
	private boolean bReceiverOn = false;
	private WifiInfo WifiInfos;

	private TextView sTvTrLog;
	private Button sBtExport, sBtImport;
	private Spinner sSpNetType;
	private XMLRPCClient sClientXMLRPC;
	private WiFiStateReceiver sWifiStateReceiver;
	private WifiManager sWiFiManager;
	private IntentFilter sFilter;

    private final String[] sFilesToImport = new String[]{"Ref_Clients.csv","Ref_Clients_Groups.csv","Ref_DocTypes.csv",
            "Ref_Firms.csv","Ref_PriceLists.csv","Ref_Products.csv","Ref_Products_Groups.csv","Ref_Products_Prices.csv"};

    private Map<String,String> MapProducts = new HashMap<String, String>();
    private Map<String,String> MapPriceLists = new HashMap<String, String>();

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
        setContentView(R.layout.transfer);

        cf = SetupRootActivity.getCurrencyFormat(this);

        sBtExport = (Button) findViewById(R.id.btExport);
		sBtImport = (Button) findViewById(R.id.btImport);

        sTvTrLog = (TextView) findViewById(R.id.tvTransferLog);
        sSpNetType = (Spinner) findViewById(R.id.spNetType);

        sBtImport.setOnClickListener(this);
        sBtExport.setOnClickListener(this);

        sDataBase = DB.get().getWritableDatabase();

        ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
        		R.array.itemNetType, android.R.layout.simple_spinner_item);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        sSpNetType.setAdapter(adapter);

        sDeviceGUID = SetupRootActivity.getGUID(TransferActivity.this);//Integer.parseInt(SetupRootActivity.getAgentID(this));
	}

	public void onClick(View v) {
		sTvTrLog.setText("");

		switch (sSpNetType.getSelectedItemPosition()) {
        case SERVER_TEST:
            if (v.getId() == R.id.btImport){
                setGuiEnabled(false);
                new ImportFromRCD().execute("Тестовые данные","test_data");
            }
            break;
		case SERVER_MOBILE:
			sURL = SetupRootActivity.getMobileServer(this);
			if (sURL.trim().length() == 0) {
				log(getString(R.string.err_ServerPort), "No setup url transfer server.");
				return;
			}
			setGuiEnabled(false);

			if (sURL.toLowerCase().indexOf("http://") < 0)
				sURL = "http://" + sURL + Const.RPC_PATH;

			if (v.getId() == R.id.btImport)
				new ImportFromRCD().execute(sURL);
			else
				new ExportToRCD().execute(sURL);
			break;

		case SERVER_WIFI:
			sURL = SetupRootActivity.getWiFiServer(this);
			if (sURL.trim().length() == 0) {
				log(getString(R.string.err_ServerPort), "No setup url transfer server.");
				return;
			}
			setGuiEnabled(false);

			if (sURL.toLowerCase().indexOf("http://") < 0)
				sURL = "http://" + sURL + Const.RPC_PATH;

			sImportFlag = v.getId() == R.id.btImport;

			bWifi_was_connected = false;

			getWiFiManager();
			if (sWiFiManager.getWifiState() == WifiManager.WIFI_STATE_ENABLED) {

				WifiInfos = sWiFiManager.getConnectionInfo();

				//log("WiFi state: "+WifiInfos.toString(), null);

				if(WifiInfos.getSSID()==null){
					log("Wifi doesn't connected to any network", "Wifi Enabled, but doesn't connected to any network");
					setGuiEnabled(true);
					return;
				}else{
					bWifi_was_connected = true;

					if (sImportFlag)	new ImportFromRCD().execute(sURL);
					else				new ExportToRCD().execute(sURL);
					break;
				}

			}else{
				sWiFiFlag = true;
				swichWiFi();
			}
		}
	}

	@Override
	protected void onStart() {
		super.onStart();
		setBtExportEnable();
	}

	@Override
	protected void onDestroy() {
		sDataBase.close();

		if (bReceiverOn) {
			unregisterReceiver(sWifiStateReceiver);
		}

		super.onDestroy();
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN &&
				sStartTransferFlag)	return true;
		else return super.onKeyDown(keyCode, event);
	}

	private void setBtExportEnable() {
        sBtExport.setEnabled(true);
		//Cursor cur = sDataBase.rawQuery("SELECT COUNT(*) + "+
        //        "(SELECT COUNT(*) FROM "+DB.TABLE_LOCATION +")"+
        //        " FROM "+DB.TABLE_DOCUMENT+" WHERE docstate ="+Const.DOCSTATE_PREPARE_SEND, null);
		//if (cur.moveToFirst()) {
		//	boolean flag = cur.getInt(0) > 0;
		//	sBtExport.setEnabled(flag);
		//} else {
		//	sBtExport.setEnabled(false);
		//}
		//cur.close();
	}

	private void setGuiEnabled(boolean flag) {
		if (!flag) sBtExport.setEnabled(false);
		else setBtExportEnable();
		sBtImport.setEnabled(flag);
	    sSpNetType.setEnabled(flag);
	}

	private void log(String msg, String error) {
		if (error == null) {
			sTvTrLog.append(msg+"\n");
		} else {
			sTvTrLog.append("\nERROR: "+error+"\n\n");
			new AlertDialog.Builder(this)
			.setMessage(msg)
			.setTitle(android.R.string.dialog_alert_title)
			.setPositiveButton(android.R.string.ok, null)
			.setCancelable(true)
			.show();
		}
	}

	private class ExportToRCD extends AsyncTask<String, String, Void> {
		@Override
		protected Void doInBackground(String... params) {
			try {
				publishProgress(getString(R.string.msg_StartExport), null);

				int send_doc_coun = 0;
				Cursor cur_docdet = null;
				Cursor cur_doc = sDataBase.rawQuery("SELECT d.*, c.name, t.paytype1or2 " +
						"FROM "+DB.TABLE_DOCUMENT+" d"+
                        " LEFT JOIN "+DB.TABLE_TYPEDOC+" t ON (d.doctype_id = t._id)" +
						" INNER JOIN "+DB.TABLE_CLIENT+" c on (d.client_uid = c.uid) " +
						"WHERE (docstate="+Const.DOCSTATE_PREPARE_SEND+
                        " OR docstate="+Const.DOCSTATE_SEND+")" , null);

				sClientXMLRPC = new XMLRPCClient(params[0],
                        SetupRootActivity.getHttpLogin(TransferActivity.this),
                        SetupRootActivity.getHttpPasswd(TransferActivity.this),
                        SetupRootActivity.getGUID(TransferActivity.this));

				QueryHelper qh_docdet = new QueryHelper(DB.TABLE_DOCUMENT_DET, null);
				//DataSet dsDocDet = new DataSet(sDataBase, DBDroidPres.TABLE_DOCUMENT_DET);
				//Integer central_id = 0;

				final List<Object> items = new ArrayList<Object>();
                Map<String, Object> mapDocsData;

                if (cur_doc.moveToFirst()) {
                    do {
						final long _id = QueryHelper.fieldByNameLong(cur_doc, QueryHelper.KEY_ID);
                        String central_uid;

                        mapDocsData = new HashMap<String, Object>();
                        mapDocsData.put("_type_",1);
                        mapDocsData.put("_id", _id);
                        mapDocsData.put("device_guid", sDeviceGUID);
                        mapDocsData.put("presventype",  QueryHelper.fieldByNameInt(cur_doc, "presventype"));
                        mapDocsData.put("client_uid", QueryHelper.fieldByNameString(cur_doc, "client_uid"));
                        mapDocsData.put("pricelist_uid", QueryHelper.fieldByNameString(cur_doc, "pricelist_uid"));
                        mapDocsData.put("firm_uid", QueryHelper.fieldByNameString(cur_doc, "firm_uid"));

                        final String CreatedTime = QueryHelper.fieldByNameString(cur_doc, "CREATED_TIME");
                        mapDocsData.put("created_time", CreatedTime);

                        central_uid = CreatedTime+" "+ sDeviceGUID;
                        mapDocsData.put("central_uid", central_uid);

						final String desc = QueryHelper.fieldByNameString(cur_doc, "description");
						if (desc.length() > 0) mapDocsData.put("description", desc);
                        mapDocsData.put("paytype", QueryHelper.fieldByNameInt(cur_doc, "paytype"));

                        if(!cur_doc.isNull(cur_doc.getColumnIndex("paytype1or2")))
                            mapDocsData.put("paytype1or2", QueryHelper.fieldByNameInt(cur_doc, "paytype1or2"));

                        if(!cur_doc.isNull(cur_doc.getColumnIndex("paymentdate")))
                            mapDocsData.put("paymentdate", QueryHelper.fieldByNameString(cur_doc, "paymentdate"));

                        mapDocsData.put("doctype_id", QueryHelper.fieldByNameInt(cur_doc, "doctype_id"));
                        mapDocsData.put("itemcount", QueryHelper.fieldByNameFloat(cur_doc, "itemcount"));
                        mapDocsData.put("mainsumm", QueryHelper.fieldByNameFloat(cur_doc, "mainsumm"));
                        items.add(mapDocsData);

                        ContentValues values = new ContentValues();
                        values.put("docstate", 2);
                        values.put("central_uid", central_uid);
                        sDataBase.update(DB.TABLE_DOCUMENT, values,
                                QueryHelper.KEY_ID + " = " + _id, null);

                        send_doc_coun++;

						qh_docdet.appendFilter("DOCUMENT_ID", QueryHelper.FILTER_AND, "order_id = %d", _id);
						if (cur_docdet != null) cur_docdet.close();
						cur_docdet = qh_docdet.createCurcor(sDataBase);
						if (cur_docdet.moveToFirst()) {
							do {
                                mapDocsData = new HashMap<String, Object>();
                                mapDocsData.put("order_id", _id);
                                mapDocsData.put("product_uid", QueryHelper.fieldByNameString(cur_docdet, "product_uid"));
                                mapDocsData.put("qty", QueryHelper.fieldByNameFloat(cur_docdet, "qty"));
                                mapDocsData.put("price", QueryHelper.fieldByNameFloat(cur_docdet, "price"));
								items.add(mapDocsData);
							} while (cur_docdet.moveToNext());
						}
					} while (cur_doc.moveToNext());
                    cur_docdet.close();
					cur_doc.close();

                    Object result = sClientXMLRPC.call("SetDocs", sDeviceGUID, items);
                    items.clear();
                }

                final Cursor cur = sDataBase.query(DB.TABLE_LOCATION, null, null, null,
                        null, null, null);
                if (cur.moveToFirst()) do {
                    Map<String, Object> row = new HashMap<String, Object>();
                    row.put("date_location", cur.getString(0));
                    row.put("provider", cur.getString(1));
                    row.put("lat", cur.getInt(2));
                    row.put("lon", cur.getInt(3));
                    row.put("accuracy", cur.getInt(4));
                    items.add(row);
                } while (cur.moveToNext());
                cur.close();
                Object result = sClientXMLRPC.call("SetLocation", sDeviceGUID, items);
                items.clear();
                if ((Boolean)result) {
                    sDataBase.delete(DB.TABLE_LOCATION, null, null);
                }

				publishProgress(getString(R.string.msg_StopExport) , null);
				publishProgress(getString(R.string.msg_SendDocCount, send_doc_coun) , null);
                deleteOldRecords();
			} catch (final XMLRPCFault e) {
				Log.e("Transfer", "XMLRPCFault", e);
				publishProgress(getString(R.string.err_XMLRPCFault), e.getMessage());
			} catch (final XMLRPCException e) {
				Throwable couse = e.getCause();
				if (couse instanceof HttpHostConnectException) {
					Log.e("Transfer", "HttpHostConnectException", e);
					publishProgress(getString(R.string.err_HttpHostConnectException), e.getMessage());
				} else if (couse instanceof SocketTimeoutException) {
					Log.e("Transfer", "SocketTimeoutException", e);
					publishProgress(getString(R.string.err_SocketTimeoutException), e.getMessage());
				} else {
					Log.e("Transfer", "XMLRPCException", e);
					publishProgress(getString(R.string.err_XMLRPCException), e.getMessage());
				}
			} catch (Exception e) {
				Log.e("Transfer", "UnknownException", e);
				publishProgress(getString(R.string.err_UnknownException), e.toString());
			}
			return null;
		}

		@Override
		protected void onProgressUpdate(String... progress) {
			log(progress[0], progress[1]);
		}

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			setProgressBarIndeterminateVisibility(true);
			sStartTransferFlag = true;
		}

		@Override
		protected void onPostExecute(Void result) {
			super.onPostExecute(result);
			setProgressBarIndeterminateVisibility(false);
			sStartTransferFlag = false;
			if (sSpNetType.getSelectedItemPosition() == SERVER_WIFI) {

				if (!bWifi_was_connected){
					sWiFiFlag = false;
					getWiFiManager().setWifiEnabled(sWiFiFlag);
				}

			}
			setGuiEnabled(true);
	     }
	}

	private class ImportFromRCD extends AsyncTask<String, String, Void> {
		@Override
		protected Void doInBackground(String... params) {
			try {
				publishProgress(getString(R.string.msg_StartImport, params[0]), null);

                boolean bItIsTestData = false;
                byte[] data = null;

                if(params.length > 1){
                    if(params[1] == "test_data") bItIsTestData = true;
                } else {
                    sClientXMLRPC = new XMLRPCClient(
                            params[0],
                            SetupRootActivity.getHttpLogin(TransferActivity.this),
                            SetupRootActivity.getHttpPasswd(TransferActivity.this),
                            SetupRootActivity.getGUID(TransferActivity.this)
                                                    );

                    final Object[] param = {sDeviceGUID};
                    data = (byte[]) sClientXMLRPC.callEx("GetZipData", param);
                }

                if(getZipArchive(data)){
                    getReferenceFromFile(sDataBase, DB.TABLE_PRODUCT_GROUP, "Ref_Products_Groups.csv",getString(R.string.msg_GetRefProductGroup));
                    getReferenceFromFile(sDataBase, DB.TABLE_PRODUCT, "Ref_Products.csv",getString(R.string.msg_GetRefProduct));
                    getReferenceFromFile(sDataBase, DB.TABLE_PRICELISTS, "Ref_PriceLists.csv",getString(R.string.msg_GetRefPriceLists));
                    getReferenceFromFile(sDataBase, DB.TABLE_PRICES, "Ref_Products_Prices.csv",getString(R.string.msg_GetRefPrices));
                    getReferenceFromFile(sDataBase, DB.TABLE_CLIENT_GROUP, "Ref_Clients_Groups.csv",getString(R.string.msg_GetRefClientGroup));
                    getReferenceFromFile(sDataBase, DB.TABLE_CLIENT, "Ref_Clients.csv",getString(R.string.msg_GetRefClient));
                    getReferenceFromFile(sDataBase, DB.TABLE_TYPEDOC, "Ref_DocTypes.csv",getString(R.string.msg_GetRefTypeDoc));
                    getReferenceFromFile(sDataBase, DB.TABLE_FIRMS, "Ref_Firms.csv",getString(R.string.msg_GetRefFirms));

                    publishProgress(getString(R.string.msg_StopImport), null);
                    //sNewVersion = getUppdateApp();
                    //deleteOldRecords();
                }else{
                    publishProgress("Ошибка при получении/распаковке архива с данными.", null);
                }

			} catch (final XMLRPCFault e) {
				Log.e("ImportFromRCD", "XMLRPCFault", e);
				publishProgress(getString(R.string.err_XMLRPCFault), e.toString());
			} catch (final IOException e) {
				Log.e("ImportFromRCD", "IOException", e);
				publishProgress(getString(R.string.err_IOException), e.toString());
			//} catch (final NameNotFoundException e) {
			//	Log.e("ImportFromRCD", "NameNotFoundException", e);
			//	publishProgress(getString(R.string.err_NameNotFoundException), e.toString());
			} catch (final XMLRPCException e) {
				Throwable couse = e.getCause();
				if (couse instanceof HttpHostConnectException) {
					Log.e("ImportFromRCD", "HttpHostConnectException", e);
					publishProgress(getString(R.string.err_HttpHostConnectException), e.toString());
				} else if (couse instanceof SocketTimeoutException) {
					Log.e("ImportFromRCD", "SocketTimeoutException", e);
					publishProgress(getString(R.string.err_SocketTimeoutException), e.toString());
				} else {
					Log.e("ImportFromRCD", "XMLRPCException", e);
					publishProgress(getString(R.string.err_XMLRPCException), e.toString());
				}
			} catch (Exception e) {
				Log.e("ImportFromRCD", "UnknownException", e);
				publishProgress(getString(R.string.err_UnknownException), e.toString());
			}

			return null;
		}

		@Override
		protected void onProgressUpdate(String... progress) {
			log(progress[0], progress[1]);
		}

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			setProgressBarIndeterminateVisibility(true);
			sStartTransferFlag = true;
		}

		@Override
		protected void onPostExecute(Void result) {
			super.onPostExecute(result);
			setProgressBarIndeterminateVisibility(false);
			sStartTransferFlag = false;
			if (sSpNetType.getSelectedItemPosition() == SERVER_WIFI) {

				if (!bWifi_was_connected){
					sWiFiFlag = false;
					getWiFiManager().setWifiEnabled(sWiFiFlag);
				}

			}
			setGuiEnabled(true);
			if (sNewVersion) updateApp();
		}

        @SuppressWarnings("unchecked")
        private void getReferenceFromFile(SQLiteDatabase db, String table_name,
                                          String file_name, String Message) throws Exception {

            final boolean bLoadingPrices = (table_name.equals(DB.TABLE_PRICES));
            final ContentValues cv = new ContentValues();

            csv.Reader reader = new csv.Reader(new InputStreamReader(new FileInputStream(temp_dir.concat(file_name)),"cp1251"))
                    .delimiter(';').ignoreComments(true).ignoreEmptyLines(true).preserveSpaces(true);

            publishProgress(Message, null);

            if(bLoadingPrices){
                MapProducts.clear();
                MapPriceLists.clear();
                Cursor cursor = db.rawQuery("SELECT _id,uid FROM "+DB.TABLE_PRODUCT, null);
                if (cursor.moveToFirst())
                    do {
                        MapProducts.put(cursor.getString(1),cursor.getString(0)); // key:uid value:_id
                    } while (cursor.moveToNext());
                cursor.close();
                cursor = db.rawQuery("SELECT _id,uid FROM "+DB.TABLE_PRICELISTS, null);
                if (cursor.moveToFirst())
                    do {
                        MapPriceLists.put(cursor.getString(1),cursor.getString(0)); // key:uid value:_id
                    } while (cursor.moveToNext());
                cursor.close();
            }
            String[] fields = QueryHelper.getFieldsOnTable(db, table_name);
            Arrays.sort(fields);

            List<String> headers = new ArrayList<String>();
            int CountTotalRecsByFile = 0;
            int CountTotalRecordsByDB = 0;

            try{
                db.beginTransaction();
                int processedCount = 0;
                int CountNewRec = 0;
                int CountUpdatedRec = 0;
                int CountDeactivatedRec = 0;
                int count=0;

                if(table_name.equals(DB.TABLE_TYPEDOC) || table_name.equals(DB.TABLE_PRICES))
                    db.execSQL("DELETE FROM " + table_name);
                else{
                    cv.put("_active",0);
                    CountTotalRecordsByDB = db.update(table_name, cv,null,null);
                }

                // int procCountCheck;
                boolean bError;

                List<String> result;
                while( (result = reader.readLine()) != null ){
                    cv.clear();
                    count++;
                    if(count==1){
                        headers = result;
                        continue;}
                    if(count==2){
                        if(result.size() == 1){
                            CountTotalRecsByFile = Integer.valueOf(result.get(0));
                            continue;}
                        Log.w(LOG_TAG,"Wrong file format?! ("+file_name+")");
                    }
                    //procCountCheck = processedCount;
                    //while (procCountCheck > (TRANSACTION_LENGTH-1)) {
                    //    procCountCheck = procCountCheck - TRANSACTION_LENGTH;
                    //    if(procCountCheck==0){db.setTransactionSuccessful(); db.endTransaction(); db.beginTransaction();}
                    //}
                    bError = false;
                    String uid_value = "";

                    processedCount++;
                    //Log.v(LOG_TAG, "Processing record: " + processedCount + "/" + CountTotalRecsByFile);
                    for (int ii=0; ii < result.size(); ii++){
                        final String _key = headers.get(ii);
                        final String _key_value = result.get(ii);

                        if(bLoadingPrices && _key.equals("product_uid")){ // TODO: sqlite product_uid-> product_id
                            if(MapProducts.containsKey(_key_value)){
                                cv.put("product_id", MapProducts.get(_key_value));
                            }else{
                                Log.w("ERR","Ошибка при загрузке цен: Продукт "+_key_value+" не найден!");
                                bError = true;
                            }
                        }else if(bLoadingPrices && _key.equals("pricelist_uid")){ // TODO: sqlite pricelist_uid-> pricelist_id
                            if(MapPriceLists.containsKey(_key_value)){
                                cv.put("pricelist_id", MapPriceLists.get(_key_value));
                            }else {
                                Log.w("ERR","Ошибка при загрузке цен: Прайс"+_key_value+" не найден!");
                                bError = true;
                            }
                        }else{
                            if(_key.equals("uid")){
                                uid_value = _key_value;
                            }else if (Arrays.binarySearch(fields, _key) >= 0) {
                                cv.put(_key, _key_value);
                                if (_key.equals("name") && (Arrays.binarySearch(fields, "name_case") >= 0)) {
                                    cv.put("name_case", _key_value.toUpperCase());
                                }
                            }
                        }
                    }
                    if(bError){
                        Log.w("ERR","Record "+processedCount+" skipped");
                        continue;}

                    if(uid_value.length()>0){
                        cv.put("_active",1);
                        int rows_updated = db.update(table_name,cv,"uid=?",new String[] {uid_value});
                        if(rows_updated==0){
                            cv.put("uid",uid_value);
                            db.insert(table_name,null,cv);
                            CountNewRec++;
                        } else CountUpdatedRec++;
                    }else{
                        db.insert(table_name,null,cv);
                        CountNewRec++;
                    }
                }

                if(processedCount != CountTotalRecsByFile){
                    Log.w(LOG_TAG,"Mismatch control count of records and fact ("+file_name+")");
                    publishProgress("Количество записей, указанное в файле("+CountTotalRecsByFile
                                    +") не соответствует фактическому("+processedCount+")",null);
                }

                db.setTransactionSuccessful();

                if(CountTotalRecordsByDB > 0)
                    CountDeactivatedRec = CountTotalRecordsByDB - CountUpdatedRec;
                publishProgress(getString(R.string.msg_ProcessedRecords, processedCount, CountNewRec, CountUpdatedRec, CountDeactivatedRec), null);

            }finally{
                db.endTransaction();
            }

        }

        private boolean getZipArchive(byte[] data) throws XMLRPCException, IOException {

            File f = new File(temp_dir);
            if(!f.isDirectory()) {
                f.mkdirs();
            }
            String[] FilesList = f.list();
            for (int i = 0; i < FilesList.length; i++) {
                if(Arrays.binarySearch(sFilesToImport,FilesList[i])>=0){
                    Log.v(LOG_TAG,"Deleting file in temp directory... ".concat(FilesList[i]));
                    File file = new File(temp_dir+FilesList[i]);
                    file.delete();
                }
            }

            if(data == null){
                String testfilefromAssets = SetupRootActivity.getDroidPresDir();
                f = new File(testfilefromAssets);
                if(!f.isDirectory()) {
                    f.mkdirs();
                }
                testfilefromAssets = testfilefromAssets.concat("AgentTest.zip");

                boolean all_ok = false;
                try{
                    File FileDest = new File(testfilefromAssets);
                    InputStream in = getAssets().open("AgentTest.zip");
                    OutputStream out = new FileOutputStream(FileDest);
                    byte[] buff = new byte[2048];
                    int len;

                    while((len=in.read(buff))>0){
                        out.write(buff,0,len);
                    }

                    in.close();
                    out.close();
                    all_ok = true;
                } catch(FileNotFoundException ex){
                    Log.e("TA_getZipArchive",ex.getMessage());
                } catch(IOException ex){
                    Log.e("TA_getZipArchive",ex.getMessage());
                }

                if(all_ok){
                    Log.d("TA_getZipArchive","all ok copying assets to sd card, decompressing file..");
                    Decompress ZipUnpack = new Decompress(testfilefromAssets, temp_dir);
                    return ZipUnpack.unzip();
                } else
                    return false;

            }

            if (data.length > 1) {
                File DroidFolder = new File(SetupRootActivity.getDroidPresDir());
                DroidFolder.mkdirs();

                String zipfilename = String.format("FromServer.zip"); //"FromServer%s.zip", sDeviceGUID
                File zipFile = new File(DroidFolder, zipfilename);
                //File zipFile = new File(SetupRootActivity.getDroidPresDir()+"FromServer.zip");
                zipFile.createNewFile();

                FileOutputStream fOut = new FileOutputStream(zipFile);
                fOut.write(data);
                fOut.flush();
                fOut.close();

                Decompress ZipUnpack = new Decompress(zipFile.getAbsolutePath(), temp_dir);

                return ZipUnpack.unzip();
            } else
                return false;
        }

		private boolean getUppdateApp() throws XMLRPCException, IOException {
			byte[] data = (byte[]) sClientXMLRPC.callEx("GetUpdateApp",
					new Object[] {MainActivity.versionCode});
			if (data.length > 1) {
				File apkFile = new File(SetupRootActivity.getApkFileName());
				apkFile.createNewFile();
				FileOutputStream fOut = new FileOutputStream(apkFile);
				fOut.write(data);
				fOut.flush();
				fOut.close();
				return true;
			} else
				return false;
		}

	}

	public void swichWiFi() {
		sWiFiConnectFlag = false;

		getWiFiManager();

		//if (sWiFiManager.getWifiState() == WifiManager.WIFI_STATE_ENABLED) {
		//	log(sWiFiManager.getConnectionInfo().toString(),"");

		//}else{

			IntentFilter filter = sFilter;
			WiFiStateReceiver receiver = sWifiStateReceiver;
			if (receiver == null) {
				receiver = new WiFiStateReceiver();
				sWifiStateReceiver = receiver;
				filter = new IntentFilter();
				filter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);
				filter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);
				sFilter = filter;
			}
			this.registerReceiver(receiver, filter);
			bReceiverOn = true;

			////getWiFiManager().setWifiEnabled(sWiFiFlag);
			sWiFiManager.setWifiEnabled(sWiFiFlag);


			if (sWiFiFlag) {
				new Timer().schedule(new TimerTask() {

					@Override
					public void run() {
						if (!sWiFiConnectFlag) {
							sWiFiFlag = false;
							getWiFiManager().setWifiEnabled(sWiFiFlag);
						}
					}
				}, 90000);
			}

		//};
		//

	}

	class WiFiStateReceiver extends BroadcastReceiver {
		@Override
		public void onReceive(Context context, Intent intent) {
			if (intent == null)	return;

			if (WifiManager.WIFI_STATE_CHANGED_ACTION.equals(intent.getAction())) {
				switch (intent.getIntExtra(WifiManager.EXTRA_WIFI_STATE, WifiManager.WIFI_STATE_UNKNOWN)) {
				case WifiManager.WIFI_STATE_DISABLING:
					log(getString(R.string.msg_WiFiState_DISABLING), null);
					break;

				case WifiManager.WIFI_STATE_DISABLED:
					log(getString(R.string.msg_WiFiState_DISABLED), null);
					break;

				case WifiManager.WIFI_STATE_ENABLING:
					log(getString(R.string.msg_WiFiState_ENABLING), null);
					break;

				case WifiManager.WIFI_STATE_ENABLED:
					log(getString(R.string.msg_WiFiState_ENABLED), null);
					break;

				default:
					log(getString(R.string.msg_WiFiState_UNKNOWN), null);
					break;
				}
			} else if (WifiManager.NETWORK_STATE_CHANGED_ACTION.equals(intent.getAction())) {
				NetworkInfo info = (NetworkInfo) intent.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO);
				switch (info.getDetailedState()) {
					case CONNECTING:
						log(getString(R.string.msg_NetworkState_CONNECTING), null);
						break;
					case OBTAINING_IPADDR:
						log(getString(R.string.msg_NetworkState_OBTAINING_IPADDR), null);
						break;
					case DISCONNECTING:
						log(getString(R.string.msg_NetworkState_DISCONNECTING), null);
						break;
					case DISCONNECTED:
						log(getString(R.string.msg_NetworkState_DISCONNECTED), null);
						break;
					case FAILED:
						log(getString(R.string.msg_NetworkState_FAILED), null);
						break;
					case CONNECTED:
						sWiFiConnectFlag = true;
						log(getString(R.string.msg_NetworkState_CONNECTED,
								getWiFiManager().getConnectionInfo().getSSID()), null);

						if (bReceiverOn) {
							unregisterReceiver(sWifiStateReceiver);
							bReceiverOn = false;
						}

						if (sWiFiFlag && !sStartTransferFlag) {
							if (sImportFlag)
								new ImportFromRCD().execute(sURL);
							else
								new ExportToRCD().execute(sURL);
						}
						break;
				default:
					break;
				}
			}
		}
	}

	private WifiManager getWiFiManager() {
		if (sWiFiManager == null) {
			sWiFiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
		}
		return sWiFiManager;
	}

	private void updateApp() {
		new AlertDialog.Builder(this)
		.setMessage(R.string.msg_UpdateApk)
		.setTitle(android.R.string.dialog_alert_title)
		.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {

			public void onClick(DialogInterface dialog, int which) {
				File apkFile = new File(SetupRootActivity.getApkFileName());
				Intent intent = new Intent(Intent.ACTION_VIEW);
				intent.setDataAndType(Uri.fromFile(apkFile), "application/vnd.android.package-archive");
				startActivity(intent);
			}
		})
		.setCancelable(false).show();
	}

    private void deleteOldRecords() {
        Calendar cl = Calendar.getInstance();
        cl.add(Calendar.DAY_OF_MONTH, -30);
        Date sqlDate = new Date(cl.getTime().getTime());
        sDataBase.execSQL("DELETE FROM "+DB.TABLE_DOCUMENT+" WHERE docstate = ? and docdate < ?",
                new Object[] {Const.DOCSTATE_SEND, sqlDate.toString()});
    }
}
